<template>
  <div class="article-edit">
    <div class="page-header">
      <h1>{{ isEdit ? '编辑文章' : '创建文章' }}</h1>
      <div class="header-actions">
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button type="primary" @click="handlePublish">发布</el-button>
      </div>
    </div>

    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        size="large"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入文章标题"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="摘要" prop="summary">
          <el-input
            v-model="form.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入文章摘要（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="封面图片">
          <div class="cover-upload">
            <el-input
              v-model="form.cover_image"
              placeholder="请输入图片URL或点击上传"
            />
            <el-upload
              :show-file-list="false"
              :before-upload="handleCoverUpload"
              accept="image/*"
            >
              <el-button type="primary">上传图片</el-button>
            </el-upload>
          </div>
          <div class="cover-preview" v-if="form.cover_image">
            <img :src="form.cover_image" alt="封面预览" />
          </div>
        </el-form-item>

        <el-form-item label="标签">
          <el-input
            v-model="form.tags"
            placeholder="请输入标签，用逗号分隔"
            maxlength="255"
          />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="20"
            placeholder="请输入文章内容"
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus'
import { useArticleStore } from '@/stores/article'
import { uploadFile } from '@/api/file'
import type { ArticleCreateRequest, ArticleUpdateRequest } from '@/types/api'

const route = useRoute()
const router = useRouter()
const articleStore = useArticleStore()

const formRef = ref<FormInstance>()

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = reactive<ArticleCreateRequest>({
  title: '',
  content: '',
  summary: '',
  cover_image: '',
  status: 0,
  tags: ''
})

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { max: 200, message: '标题长度不能超过200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ],
  summary: [
    { max: 500, message: '摘要长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 封面图片上传
const handleCoverUpload: UploadProps['beforeUpload'] = async (file) => {
  try {
    const response = await uploadFile(file)
    form.cover_image = response.file_url
    ElMessage.success('图片上传成功')
  } catch (error) {
    console.error('图片上传失败:', error)
  }
  return false // 阻止默认上传行为
}

// 保存草稿
const handleSaveDraft = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    form.status = 0
    
    if (isEdit.value) {
      await articleStore.updateArticle(Number(route.params.id), form as ArticleUpdateRequest)
    } else {
      await articleStore.createArticle(form)
    }
    
    router.push('/admin/articles')
  } catch (error) {
    console.error('保存草稿失败:', error)
  }
}

// 发布文章
const handlePublish = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    form.status = 1
    
    if (isEdit.value) {
      await articleStore.updateArticle(Number(route.params.id), form as ArticleUpdateRequest)
    } else {
      await articleStore.createArticle(form)
    }
    
    router.push('/admin/articles')
  } catch (error) {
    console.error('发布文章失败:', error)
  }
}

// 初始化编辑数据
onMounted(async () => {
  if (isEdit.value) {
    const articleId = Number(route.params.id)
    try {
      await articleStore.fetchArticle(articleId)
      const article = articleStore.currentArticle
      if (article) {
        form.title = article.title
        form.content = article.content
        form.summary = article.summary || ''
        form.cover_image = article.cover_image || ''
        form.status = article.status
        form.tags = article.tags || ''
      }
    } catch (error) {
      console.error('获取文章数据失败:', error)
      router.push('/admin/articles')
    }
  }
})
</script>

<style lang="scss" scoped>
.article-edit {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      margin: 0;
      color: var(--text-primary);
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .cover-upload {
    display: flex;
    gap: 10px;
    align-items: center;
    
    .el-input {
      flex: 1;
    }
  }
  
  .cover-preview {
    margin-top: 10px;
    
    img {
      max-width: 200px;
      max-height: 150px;
      border-radius: 4px;
      object-fit: cover;
    }
  }
}
</style>
